package controller;

import model.Group;
import model.GroupDAO;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/updateGroup")
public class UpdateGroupServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");

        PrintWriter out = response.getWriter();

        try {
            // 确保正确获取参数
            String idParam = request.getParameter("id");
            String nameParam = request.getParameter("name");

//            打印日志
            System.out.println("Received ID: " + idParam);
            System.out.println("Received Name: " + nameParam);

            if (idParam == null || idParam.isEmpty() || nameParam == null || nameParam.isEmpty()) {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                out.write("{\"message\": \"ID 和名称不能为空\"}");
                return;
            }

            int groupId = Integer.parseInt(idParam);
            String newName = nameParam;

            GroupDAO groupDAO = new GroupDAO();
            Group group = new Group(groupId, newName);

            boolean success = groupDAO.updateGroup(group);
            if (success) {
                out.write("{\"message\": \"小组更新成功\"}");
            } else {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                out.write("{\"message\": \"小组更新失败\"}");
            }
        } catch (NumberFormatException e) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            out.write("{\"message\": \"无效的小组ID\"}");
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            out.write("{\"message\": \"服务器内部错误\"}");
        } finally {
            out.flush();
        }
    }
}
